import sys
import traceback

class CodeObject:
	def __init__(self,code,label='Unknown_code',startln=0):
		self.code = code
		self.label = label
		self.startln = startln
		
	def execute(self,env,envlocal=None):
		try:
			if envlocal:
				exec ''.join(self.code) in env,envlocal
			else:
				exec ''.join(self.code) in env
		except Exception as e:
			if isinstance(e,SyntaxError):
				fn = e.filename
				if fn == '<module>':
					print self.label+': execution error during \'',self.code[e.lineno-1][:-1],'\' on line',e.lineno+self.startln+1
			else:
				tb = sys.exc_info()[2]
				_,lineno,fn,_ = traceback.extract_tb(tb)[-1]
				if fn == '<module>':
					print self.label+': execution error during \'',self.code[lineno-1][:-1],'\' on line',lineno+self.startln
			raise


class CodeParser:
	def __init__(self,env):
		self.nameDict = env
	
	def parse(self, code, start):
		obj = CodeObject(code,'CODE',start)
		obj.execute(self.nameDict)
		
